package com.hoppinzq.service.ssh;

import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.hoppinzq.service.aop.annotation.*;
import com.hoppinzq.service.bean.*;
import com.hoppinzq.service.cache.SSHCache;
import com.hoppinzq.service.cache.SSHConnectCache;
import com.hoppinzq.service.cache.apiCache;
import com.hoppinzq.service.exception.ResultReturnException;
import com.hoppinzq.service.util.RedisUtils;
import com.hoppinzq.service.util.UUIDUtil;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSchException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @author: zq
 */
@ApiServiceMapping(title = "ssh服务", description = "ssh服务",roleType = ApiServiceMapping.RoleType.RIGHT)
public class SSHService {
    @Autowired
    private RedisUtils redisUtils;

    @ApiMapping(value = "sshLogin", title = "ssh登录")
    public String sshLogin(String username,String password,int port,String ipAddress){
        SSHBean sshBean=null;
        if(port<=0){
            sshBean=new SSHBean(ipAddress,username,password);
        }else{
            sshBean=new SSHBean(ipAddress,port,username,password);
        }
        try{
            sshBean.sshRemoteLogin();
        }catch (Exception ex){
           throw new ResultReturnException("登录失败",4001);
        }
        if(sshBean.isLogin()){
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("username",username);
            jsonObject.put("ipAddress",ipAddress);
            if(port>0){
                jsonObject.put("port",port);
            }
            jsonObject.put("password",password);
            jsonObject.put("loginTime",new Date().getTime());
            jsonObject.put("expireTime",60*60*24);
            //if(time<=0) time=60*60*24;
            String sshToken=UUIDUtil.getUUID();
            SSHConnectCache.cache.put(sshToken, jsonObject);
            return sshToken;
        }else{
            throw new ResultReturnException("登录失败",4001);
        }
    }


    @ApiMapping(value = "change", title = "改变接口鉴权")
    public void change(){
        List<ServiceApiBean> serviceApiBeans= apiCache.outApiList;
        for(ServiceApiBean serviceApiBean:serviceApiBeans){
            List<ServiceMethodApiBean> serviceMethods=serviceApiBean.getServiceMethods();
            for(ServiceMethodApiBean serviceMethodApiBean:serviceMethods){
                if("redis".equals(serviceMethodApiBean.getServiceMethod())||"nginx".equals(serviceMethodApiBean.getServiceMethod())||"node".equals(serviceMethodApiBean.getServiceMethod())){
                    serviceMethodApiBean.setMethodRight(ApiMapping.RoleType.NO_RIGHT);
                }
            }
        }
    }

    @ApiMapping(value = "redis", title = "启动redis", description = "启动redis",roleType = ApiMapping.RoleType.ADMIN)
    public void redis() throws Exception {
        SSHBean sshBean= new SSHBean();
        sshBean.sshRemoteLogin();
        SSHCache.sshMap.put(UUIDUtil.getUUID(),sshBean);
        ChannelExec channelExec = (ChannelExec) sshBean.getSession().openChannel("exec");
        try {
            channelExec.setCommand("cd .. && cd /usr/local/bin && redis-server redis.conf");
            channelExec.connect();
        } catch (JSchException e) {
            e.printStackTrace();
        }  catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channelExec != null) {
                channelExec.disconnect();
            }
        }
    }

    @ApiMapping(value = "nginx", title = "启动nginx", description = "启动nginx",roleType = ApiMapping.RoleType.ADMIN)
    public void nginx() throws Exception {
        SSHBean sshBean= new SSHBean();
        sshBean.sshRemoteLogin();
        SSHCache.sshMap.put(UUIDUtil.getUUID(),sshBean);
        ChannelExec channelExec = (ChannelExec) sshBean.getSession().openChannel("exec");
        try {
            channelExec.setCommand("cd .. && cd /usr/local/nginx/sbin && ./nginx");
            channelExec.connect();
        } catch (JSchException e) {
            e.printStackTrace();
        }  catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channelExec != null) {
                channelExec.disconnect();
            }
        }
    }

    @ApiMapping(value = "node", title = "启动node", description = "启动node",roleType = ApiMapping.RoleType.ADMIN)
    public void node(String command) throws Exception {
        SSHBean sshBean= new SSHBean();
        sshBean.sshRemoteLogin();
        SSHCache.sshMap.put(UUIDUtil.getUUID(),sshBean);
        ChannelExec channelExec = (ChannelExec) sshBean.getSession().openChannel("exec");
        try {
            channelExec.setCommand("cd .. && cd /home/NeteaseCloudMusicApi-master/NeteaseCloudMusicApi-master && forever start -l forever.log -a app.js ");
            channelExec.connect();
        } catch (JSchException e) {
            e.printStackTrace();
        }  catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channelExec != null) {
                channelExec.disconnect();
            }
        }
    }

}

